package com.smart.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.smart.model.RanCode;
import com.smart.util.DBUtil;

public class RanCodeDAO {
  public boolean isUserIdExist(int userId) throws SQLException
  {
        String sql="select * from rancode where user_id=?";
        Connection conn = DBUtil.getConnection();
		PreparedStatement pSt = conn.prepareCall(sql);
		pSt.setInt(1, userId);
		ResultSet res=pSt.executeQuery();
		if(res.next())
		{
			return true;
		}
		return false;
  }
  public int insert(int userId,String identifier) throws SQLException
  {
     String sql="insert into rancode(user_id,identifier) values(?,?)";
     Connection conn = DBUtil.getConnection();
	 PreparedStatement pSt = conn.prepareCall(sql);
	 pSt.setInt(1, userId);
	 pSt.setString(2, identifier);
	 return pSt.executeUpdate();
  }
  
  
  public int updateIdentifier(String identifier,int userId) throws SQLException
  {
	  String sql="update rancode set identifier=? where user_id=?";
	  Connection conn = DBUtil.getConnection();
	  PreparedStatement pSt = conn.prepareCall(sql);
	  pSt.setString(1,identifier);
	  pSt.setInt(2, userId);
	  return pSt.executeUpdate();
  }
  
  public RanCode getRanCode(int userId) throws SQLException
  {
	  RanCode ranCode=null;
	  String sql="select identifier,create_time from rancode where user_id=?";
	  Connection conn = DBUtil.getConnection();
	  PreparedStatement pSt = conn.prepareCall(sql);
	  pSt.setInt(1, userId);
	  ResultSet res=pSt.executeQuery();
	  if(res.next()) 
	  {
		  ranCode=new RanCode();
		  ranCode.setIdentifier(res.getString("identifier"));
		  ranCode.setCreate_time(res.getTimestamp("create_time").getTime());
		  ranCode.setUserId(userId);
	  }
	  return ranCode;
  }
}
